<template>
  <div class="report-container">
    <div
      style="
        margin-bottom: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      "
    >
      <a-button @click="back">返回</a-button>
      <div>
        <a-button
          v-auth="'expense:write'"
          v-if="shouldDisplayContent"
          @click="submit"
          type="primary"
          >提交报表</a-button
        >
        <!-- <a-button
          v-auth="'expense:write'"
          v-if="shouldDisplayContent"
          @click="addRow"
          style="margin-left: 20px"
          >添加行</a-button
        > -->
        <a-button
          v-auth="'expense:download'"
          @click="expertDerive"
          style="margin-left: 20px"
          >导出报表</a-button
        >
        <a-button
          v-auth="'expense:outautid'"
          v-if="showBtn"
          @click="financeVerify()"
          style="margin-left: 20px"
          >财务审核</a-button
        >
        <a-button
          v-auth="'expense:inautid'"
          @click="directorVerify()"
          style="margin-left: 20px"
          >科室主任审核</a-button
        >

        <a-button
          v-auth="'expense:export'"
          @click="exportBankTable"
          style="margin-left: 20px"
          >导出银行报表</a-button
        >
      </div>
    </div>

    <div style="display: flex">
      <div style="position: relative; top: 113px">
        <span
          style="width: max-content; display: inline-block; margin-right: 10px"
          >金额汇总人
        </span>
        <a-checkbox-group v-model="checkedList" @change="jehzrChange">
          <div
            style="width: 100%; height: 40px; line-height: 40px"
            v-for="(row, rowIndex) in dataSource"
            :key="rowIndex"
          >
            <a-checkbox :value="rowIndex"></a-checkbox>
          </div>
        </a-checkbox-group>
      </div>
      <div style="position: relative; top: 113px">
        <span style="width: max-content; display: inline-block">汇总人</span>
        <a-checkbox-group v-model="hzrArr" @change="hzrChange">
          <div
            style="width: 100%; height: 40px; line-height: 40px"
            v-for="(row, rowIndex) in dataSource"
            :key="rowIndex"
          >
            <a-checkbox :value="rowIndex"></a-checkbox>
          </div>
        </a-checkbox-group>
      </div>

      <table
        border="1"
        style="margin-left: 10px"
        :class="
          shouldDisplayContent && checkAuth('expense:write') ? '' : 'isHide'
        "
      >
        <thead>
          <tr>
            <th rowspan="3" style="width: 100px">序号</th>
            <th rowspan="3" style="width: 100px">姓名</th>
            <th colspan="13">夜餐及公杂费</th>
            <th style="width: 100px">通讯费</th>
            <th rowspan="3" style="width: 100px">领取金额</th>
            <th rowspan="3" style="width: 100px">备注</th>
          </tr>
          <tr>
            <th colspan="6">办案人员</th>
            <th colspan="6">辅助办案人员</th>
            <th rowspan="2" style="width: 60px">合计</th>
            <th rowspan="2" style="width: 60px">标准/月</th>
          </tr>
          <tr>
            <th style="width: 150px">办案人员工作日标准</th>
            <th style="width: 60px">天数</th>
            <th style="width: 60px">小计</th>
            <th style="width: 150px">办案人员 公休日节假日标准</th>
            <th style="width: 60px">天数</th>
            <th style="width: 60px">小计</th>
            <th style="width: 150px">辅助办案人员工作日标准</th>
            <th style="width: 60px">天数</th>
            <th style="width: 60px">小计</th>
            <th style="width: 150px">辅助办案人员 公休日节假日标准</th>
            <th style="width: 60px">天数</th>
            <th style="width: 60px">小计</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in dataSource" :key="rowIndex">
            <td v-for="(item, itemIndex) in row" :key="itemIndex">
              <template v-if="itemIndex === 0">
                {{ rowIndex + 1 }}
              </template>
              <template v-else>
                <template v-if="itemIndex != 1 && itemIndex != 17">
                  <input
                    @change="(e) => inputChange(e, rowIndex, itemIndex, item)"
                    onkeyup="value = value.replace(/\D/g, '')"
                    style="border: 0; width: 100%"
                    :value="item.value"
                    :disabled="
                      itemIndex == 2 ||
                      itemIndex == 5 ||
                      itemIndex == 8 ||
                      itemIndex == 11
                    "
                  />
                </template>
                <template v-else>
                  <input
                    @change="(e) => inputChange(e, rowIndex, itemIndex, item)"
                    style="border: 0; width: 100%"
                    :value="item.value"
                    :disabled="
                      itemIndex == 2 ||
                      itemIndex == 5 ||
                      itemIndex == 8 ||
                      itemIndex == 11
                    "
                  />
                </template>
              </template>
            </td>
          </tr>
          <tr>
            <td :key="index" v-for="(item, index) in total">
              {{ item.value }}
            </td>
          </tr>
        </tbody>
      </table>
      <div style="position: relative; top: 137px" v-auth="'expense:hangremove'">
        <div
          style="width: 30px; height: 40px; line-height: 40px"
          v-for="(row, rowIndex) in dataSource"
          :key="rowIndex"
          @click="deleteRow(row, rowIndex)"
        >
          <a-icon
            type="minus-circle"
            :style="{
              'font-size': '20px',
              cursor: 'pointer',
            }"
          />
        </div>
      </div>
    </div>
    <a-modal
      title="财务审核"
      :visible="financeVerifyVisible"
      :destroyOnClose="true"
      @ok="financeVerifyHandleOk"
      @cancel="financeVerifyHandleCancel"
      :width="800"
    >
      <a-form
        :form="financeVerifyForm"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="审批结果">
          <a-radio-group
            v-decorator="[
              'financeResult',
              {
                rules: [{ required: true, message: '请选择审批结果!' }],
                initialValue: '通过',
              },
            ]"
          >
            <a-radio value="通过">通过</a-radio>
            <a-radio value="不通过">不通过</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="审批反馈">
          <a-input
            placeholder="审批反馈"
            v-decorator="[
              'financeFeedback',
              {
                initialValue: financeVerifyForm.financeFeedback,
              },
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      title="科室审核"
      :visible="directorVerifyVisible"
      :destroyOnClose="true"
      @ok="directorVerifyHandleOk"
      @cancel="directorVerifyHandleCancel"
      :width="800"
    >
      <a-form
        :form="directorVerifyForm"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="审批结果">
          <a-radio-group
            v-decorator="[
              'directorResult',
              {
                rules: [{ required: true, message: '请选择审批结果!' }],
                initialValue: '通过',
              },
            ]"
          >
            <a-radio value="通过">通过</a-radio>
            <a-radio value="不通过">不通过</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="审批反馈">
          <a-input
            placeholder="审批反馈"
            v-decorator="[
              'directorFeedback',
              {
                initialValue: directorVerifyForm.directorFeedback,
              },
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import {
  getApprovalDetail,
  insertgai2,
  searchDetailListGai2,
  expertDerive,
  financeUpdate,
  directorUpdate,
  expertBankDerive,
} from '@/api/report';
import Cookies from 'js-cookie';
import _ from 'lodash';
export default {
  name: 'report',
  components: {},
  data() {
    return {
      dataSource: [],
      id: '',
      directorResult: '',
      financeResult: '',
      total: [
        { value: '合计' },
        { value: '' },
        { value: '' },
        { value: 0 },
        { value: 0 },
        { value: '' },
        { value: 0 },
        { value: 0 },
        { value: '' },
        { value: 0 },
        { value: 0 },
        { value: '' },
        { value: 0 },
        { value: 0 },
        { value: 0 },
        { value: '' },
        { value: 0 },
        { value: '' },
      ],
      financeVerifyForm: this.$form.createForm(this, {
        financeResult: undefined,
        financeFeedback: undefined,
      }),
      directorVerifyForm: this.$form.createForm(this, {
        directorResult: undefined,
        directorFeedback: undefined,
      }),
      financeVerifyVisible: false,
      directorVerifyVisible: false,
      userIds: [],
      hzrArr: [], //汇总人
      checkedList: [],
    };
  },
  mounted() {
    const id = this.$route.query.id;
    const directorResult = this.$route.query.directorResult;
    const financeResult = this.$route.query.financeResult;
    this.id = id;
    this.directorResult = directorResult;
    this.financeResult = financeResult;
    console.log(directorResult);
    console.log(financeResult);

    searchDetailListGai2({ id }).then((res) => {
      console.log(res);

      let data = _.cloneDeep(res.data);
      data.forEach((array, index) => {
        array.forEach((item, index1) => {
          if (index1 == 18) {
            this.userIds.push(item);
          }
        });
      });
      data.forEach((array, index) => {
        if (array.length > 1) {
          array.pop();
        }
      });
      console.log(this.userIds);
      console.log(data);
      this.dataSource = data;
      const columnsToTotal = [3, 4, 6, 7, 9, 10, 12, 13, 14, 16];
      const columnSums = {};
      columnsToTotal.forEach((columnIndex) => {
        columnSums[columnIndex] = 0;
      });

      res.data.forEach((row) => {
        row.forEach((cell, index) => {
          if (columnsToTotal.includes(index)) {
            columnSums[index] += parseInt(cell.value) || 0;
          }
        });
      });

      columnsToTotal.forEach((columnIndex) => {
        this.total[columnIndex].value = columnSums[columnIndex];
      });
    });
  },
  computed: {
    shouldDisplayContent() {
      console.log(
        !(this.directorResult === '通过' && this.financeResult !== '不通过')
      );
      return !(
        this.directorResult === '通过' && this.financeResult !== '不通过'
      );
    },
    showBtn() {
      return this.directorResult === '通过';
    },
  },
  methods: {
    inputChange(e, rowIndex, itemIndex, item) {
      const { value } = e.target;
      this.dataSource[rowIndex][itemIndex].value = value;

      let subtotal1Item = this.dataSource[rowIndex][4];

      let subtotal2Item = this.dataSource[rowIndex][7];
      let subtotal3Item = this.dataSource[rowIndex][10];
      let subtotal4Item = this.dataSource[rowIndex][13];

      let caseHandlersWorkingStandardsItem = this.dataSource[rowIndex][2];
      let caseHandlersWorkingStandardsDaysItem = this.dataSource[rowIndex][3];
      subtotal1Item.value =
        (parseInt(caseHandlersWorkingStandardsItem.value) || 0) *
        (parseInt(caseHandlersWorkingStandardsDaysItem.value) || 0);

      let caseHandlersHolidaysItem = this.dataSource[rowIndex][5];
      let caseHandlersHolidaysDaysItem = this.dataSource[rowIndex][6];
      subtotal2Item.value =
        (parseInt(caseHandlersHolidaysItem.value) || 0) *
        (parseInt(caseHandlersHolidaysDaysItem.value) || 0);

      let auxiliaryCaseHandlersWorkingStandardsItem =
        this.dataSource[rowIndex][8];
      let auxiliaryCaseHandlersWorkingStandardsDaysItem =
        this.dataSource[rowIndex][9];
      subtotal3Item.value =
        (parseInt(auxiliaryCaseHandlersWorkingStandardsItem.value) || 0) *
        (parseInt(auxiliaryCaseHandlersWorkingStandardsDaysItem.value) || 0);

      let auxiliaryCaseHandlersHolidaysItem = this.dataSource[rowIndex][11];
      let auxiliaryCaseHandlersHolidaysDaysItem = this.dataSource[rowIndex][12];
      subtotal4Item.value =
        (parseInt(auxiliaryCaseHandlersHolidaysItem.value) || 0) *
        (parseInt(auxiliaryCaseHandlersHolidaysDaysItem.value) || 0);

      let totalItem = this.dataSource[rowIndex][14];
      totalItem.value =
        subtotal1Item.value +
        subtotal2Item.value +
        subtotal3Item.value +
        subtotal4Item.value;

      let claimAmount = this.dataSource[rowIndex][16];
      let communicationExpenses = this.dataSource[rowIndex][15];
      claimAmount.value =
        (parseInt(communicationExpenses.value) || 0) +
        (parseInt(totalItem.value) || 0);

      //合计
      const columnsToTotal = [3, 4, 6, 7, 9, 10, 12, 13, 14, 16];

      const columnSums = {};
      columnsToTotal.forEach((columnIndex) => {
        columnSums[columnIndex] = 0;
      });

      this.dataSource.forEach((row) => {
        row.forEach((cell, index) => {
          if (columnsToTotal.includes(index)) {
            columnSums[index] += parseInt(cell.value) || 0;
          }
        });
      });

      columnsToTotal.forEach((columnIndex) => {
        this.total[columnIndex].value = columnSums[columnIndex];
      });
    },
    submit() {
      console.log(this.userIds);
      let code = _.cloneDeep(this.dataSource);
      code = code.map((row, indexs) => {
        return row
          .map((item, index) => {
            if (item.value === '') {
              item.value = '0';
            }
            if (index == 17 && (item.value == null || item.value == 0)) {
              //备注
              item.value = '';
            }
            return item;
          })
          .concat({
            name: '18',
            value: this.id,
          })
          .concat({
            name: '19',
            value: this.userIds[indexs].value,
          });
      });
      insertgai2(code).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success('提交成功');
          this.$router.push('/report');
        }
      });
    },
    addRow() {
      this.dataSource.push([
        {
          name: '0',
        },
        {
          name: '1',
          value: '',
        },
        {
          name: '2',
          value: '70',
        },
        {
          name: '3',
          value: '',
        },
        {
          name: '4',
          value: '',
        },
        {
          name: '5',
          value: '140',
        },
        {
          name: '6',
          value: '',
        },
        {
          name: '7',
          value: '',
        },
        {
          name: '8',
          value: '55',
        },
        {
          name: '9',
          value: '',
        },
        {
          name: '10',
          value: '',
        },
        {
          name: '11',
          value: '110',
        },
        {
          name: '12',
          value: '',
        },
        {
          name: '13',
          value: '',
        },
        {
          name: '14',
          value: '',
        },
        {
          name: '15',
          value: '',
        },
        {
          name: '16',
          value: '',
        },
        {
          name: '17',
          value: '',
        },
      ]);
    },
    back() {
      this.$router.push('/report');
    },
    expertDerive() {
      expertDerive({
        approvalId: this.id,
      }).then((response) => {
        const blob = new Blob([response]);
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        const timestamp = new Date()
          .toISOString()
          .replace(/[-T:]/g, '')
          .slice(0, 14);
        const fileName = `${timestamp}.xlsx`;
        link.href = url;
        link.download = fileName;
        link.click();
      });
    },
    deleteRow(row, index) {
      this.dataSource.splice(index, 1);
      this.hzrArr = [];
      this.checkedList = [];
    },
    financeVerify() {
      this.financeVerifyVisible = true;
    },
    financeVerifyHandleOk(e) {
      e.preventDefault();
      this.financeVerifyForm.validateFields((err, values) => {
        if (!err) {
          let request = { ...values, id: this.id };
          financeUpdate(request).then((response) => {
            console.log(response);
            if (response.code == 200) {
              this.$message.success(response.message);
              this.financeVerifyVisible = false;
            } else {
              this.$message.error(response.message);
            }
          });
        }
      });
    },
    financeVerifyHandleCancel() {
      this.financeVerifyVisible = false;
    },
    directorVerify() {
      this.directorVerifyVisible = true;
    },
    directorVerifyHandleOk(e) {
      e.preventDefault();
      this.directorVerifyForm.validateFields((err, values) => {
        if (!err) {
          let request = { ...values, id: this.id };
          directorUpdate(request).then((response) => {
            console.log(response);
            if (response.code == 200) {
              this.$message.success(response.message);
              this.directorVerifyVisible = false;
            } else {
              this.$message.error(response.message);
            }
          });
        }
      });
    },
    directorVerifyHandleCancel() {
      this.directorVerifyVisible = false;
    },
    checkAuth(permission) {
      const userPermissions = JSON.parse(Cookies.get('permissions')) || [];
      return userPermissions.includes(permission);
    },
    exportBankTable() {
      if (this.hzrArr.length == 0) {
        this.$message.info('请勾选汇总人');
        return;
      }

      let hzr = [];
      let jehzr = '';
      this.hzrArr.forEach((item) => {
        hzr.push(this.userIds[item].value);
      });
      this.checkedList.forEach((item) => {
        jehzr = this.userIds[item].value;
      });
      let beSummarizedUserIds = hzr.join(',');
      let collectUserId = jehzr;
      let req = {
        approvalId: this.id,
        beSummarizedUserIds, //汇总人
        collectUserId, //金额汇总人
      };

      expertBankDerive(req).then((response) => {
        console.log(response);
        const blob = new Blob([response]);
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        const timestamp = new Date()
          .toISOString()
          .replace(/[-T:]/g, '')
          .slice(0, 14);
        const fileName = `${timestamp}.xlsx`;
        link.href = url;
        link.download = fileName;
        link.click();
      });
    },
    jehzrChange(checkedList) {
      this.checkedList =
        checkedList.length > 1 ? checkedList.slice(1) : checkedList;

      if (this.checkedList.length > 0) {
        if (!this.hzrArr.includes(parseInt(this.checkedList.join(',')))) {
          this.hzrArr.push(parseInt(this.checkedList.join(',')));
        }
      }
      console.log(this.checkedList);
    },
    hzrChange(val) {
      this.hzrArr = val;
      console.log(this.hzrArr);
    },
  },
};
</script>

<style lang="scss" scoped>
::-webkit-scrollbar {
  width: 0 !important;
}
.report-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: scroll;

  .isHide {
    pointer-events: none;
  }
}

table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  border: 1px solid black;
  padding: 8px;
  text-align: center;
}

th {
  background-color: #f2f2f2;
}

th:first-child {
  width: 50px;
}

td:first-child {
  text-align: left;
}
</style>
